#include "socket_handler.h"
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

bool SocketHandler::SocketBind()
{
	listenFd = socket(AF_INET, SOCK_STREAM, 0);
	if(listenFd == -1) {
		printf("creat socket failed.\n");
		return false;
	}

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	int ret = inet_pton(AF_INET, ip.c_str(), (void*)&(addr.sin_addr));
	if(ret != 1) {
        printf("get network byte order binary address failed.\n");
        return false;
    }// else {
        //printf("inet_pton ip address: 0x%x\n", addr.sin_addr.s_addr);
    //}
	//
	addr.sin_port = htons((uint16_t)port);

	ret = bind(listenFd, (struct sockaddr*)&addr, sizeof(addr));
	if(ret < 0) {
		printf("bind ip:0.0.0.0, port:%u failed, erron:%d\n",
				port, errno);
		close(listenFd);
		return false;
	}
	return true;
}

bool SocketHandler::SocketListen()
{
	int ret = listen(listenFd ,LISNTENQ);
	if(ret < 0) {
		printf("listen scoket failed, errno:%d\n", errno);
		close(listenFd);
		return false;
	}
	return true;
}

int SocketHandler::HandlerAccept()
{
	int childFd = accept(listenFd, NULL, NULL);
	if(childFd == -1) {
		printf("Accept failed.\n");
	}
	return childFd;
}

string SocketHandler::DoRead(int fd)
{
	char buf[MAXSIZE];
	memset(buf, '\0', MAXSIZE);
	int nread = read(fd, buf, MAXSIZE);

	string str;
	if(nread <= 0) {
		return str;
	} else {
		str = buf;
		return str;
	}
}

bool SocketHandler::DoWrite(int fd, string str){
	int nwrite = write(fd, str.c_str(), str.size() + 1);
	if(nwrite == -1) {
		return false;
	}
	return true;
}

void SocketHandler::SocketUinit(){
	close(listenFd);
}

